<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
      <el-breadcrumb-item>支部管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select
            v-model="queryInfo.branch"
            placeholder="请选择党支部"
            @change="branchChange"
          >
            <el-option
              v-for="(item, index) in branch"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            placeholder="请输入搜索内容"
            v-model="query.name"
            clearable
            @clear="getBranchUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchMemberByName"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加党支部</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="info" @click="judge">支部成员批量转移</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        id="rebateSetTable"
        :data="userlist"
        border
        stripe
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <!-- stripe: 斑马条纹
        border：边框-->
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="teacherID" label="ID"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phoneNumber" label="电话"></el-table-column>
        <el-table-column prop="partyBranch" label="党支部"></el-table-column>
        <el-table-column
          prop="isBranchLeader"
          label="是否是党支部领导"
        ></el-table-column>
        <el-table-column
          prop="isPayThisMonth"
          label="本月是否缴纳过党费"
        ></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="showEditDialog(scope.row.teacherID)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="removeUserByName(scope.row.name)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              :enterable="false"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加党支部的对话框 -->
    <el-dialog
      title="添加党支部"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addBranchForm"
        ref="addBranchFormRef"
        :rules="addBranchFormRules"
        label-width="100px"
      >
        <el-form-item label="党支部名字" prop="name">
          <el-input v-model="addBranchForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBranch">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量转移支部成员选择目标党支部的对话框 -->
    <el-dialog
      title="批量转移"
      :visible.sync="moveDialogVisible"
      width="50%"
      @close="moveDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="moveMembersInfo"
        ref="moveBranchFormRef"
        label-width="100px"
      >
        <el-form-item label="党支部名字" prop="targetBranch">
          <el-select
            v-model="moveMembersInfo.targetBranch"
            placeholder="请选择党支部"
          >
            <el-option
              v-for="(item, index) in branch"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="moveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="moveMembers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改党员信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="editUserForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="党支部" prop="partyBranch">
          <el-select
            v-model="editUserForm.partyBranch"
            placeholder="请选择党支部"
          >
            <el-option
              v-for="(item, index) in branch"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否领导" prop="isBranchLeader">
          <el-switch v-model="editUserForm.isBranchLeader"></el-switch>
        </el-form-item>
        <el-form-item label="交钱数" prop="dues">
          <el-input v-model="editUserForm.dues"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      // 返回一个错误提示
      callback(new Error("请输入合法的手机号码"));
    };

    return {
      //加载
      loading:false,
      // 获取用户列表查询参数对象
      queryInfo: {
        //支部ID
        branch: "",
        // 当前页数
        pagenum: 1,
        // 每页显示多少数据
        pagesize: 5,
      },
      query: { name: "" },
      userlist: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 党支部添加
      addBranchForm: {
        name: "",
      },
      moveDialogVisible: false,
      //支部成员批量转移数据
      moveMembersInfo: {
        teacherIDs: "",
        targetBranch: "",
      },
      multipleSelection: [],
      //用户添加中的党支部下拉框数据
      branch: [],
      // 用户添加表单验证规则
      addBranchFormRules: {
        name: [
          { required: true, message: "请输入党支部名字", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "姓名的长度在2～10个字",
            trigger: "blur",
          },
        ],
      },
      // 修改用户
      editTeacherID: {
        teacherID: "",
      },
      editDialogVisible: false,
      editUserForm: {},
      tempeditUserForm: {
        teacherID: "",
        phoneNumber: "",
        partyBranch: "",
        isBranchLeader: "",
        dues: "",
      },
      // 编辑用户表单验证
      editUserFormRules: {
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 当前需要被分配角色的用户
      userInfo: {},
      // 所有角色数据列表
      rolesLsit: [],
      // 已选中的角色Id值
      selectRoleId: "",
    };
  },
  created() {
    //this.getBranchUserList();
    this.getBranchs();
  },
  methods: {
    branchChange() {
      this.getBranchUserList();
    },
    async getBranchUserList() {
      this.loading=true;
      const { data: res } = await this.$http.get("branchMemberList", {
        params: this.queryInfo,
      });
      console.log(res);
      this.loading=false;
      this.userlist = res.partyMemberList;
      this.total = res.total;
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getBranchUserList();
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagenum = newSize;
      this.getBranchUserList();
    },

    // 第一列多选框选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
      var temp = [];
      val.forEach((e) => {
        temp.push(e.teacherID);
      });
      var tempstring = "";
      for (var i = 0; i < temp.length; i++) {
        tempstring = tempstring + temp[i] + ",";
      }
      console.log(tempstring);
      this.moveMembersInfo.teacherIDs = tempstring;
      console.log(this.moveMembersInfo.teacherIDs);
    },
    //判断是否选择成员
    judge() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请先选择要转移的党员！");
      } else {
        this.moveDialogVisible = true;
      }
    },

    //支部成员批量转移
    async moveMembers() {
      console.log(this.moveMembersInfo);
      console.log(this.$qs.stringify(this.moveMembersInfo));
      const { data: res } = await this.$http.post(
        "moveMembers",
        this.$qs.stringify(this.moveMembersInfo)
      );
      this.$message.success("转移成功！");
      // 隐藏添加用户对话框
      this.moveDialogVisible = false;
      this.getBranchUserList();
    },

    //搜索用户
    async searchMemberByName() {
      //var name=this.query
      const { data: res } = await this.$http.get("searchMemberByName", {
        params: this.query,
      });
      console.log(res);
      this.userlist = res;
      this.total = undefined;
      console.log(this.userlist);
    },
    // 监听 添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addBranchFormRef.resetFields();
    },
    // 监听 批量转移对话框的关闭事件
    moveDialogClosed() {
      this.$refs.moveBranchFormRef.resetFields();
    },
    //添加用户之前获取初始化党支部下拉框的数据
    async getBranchs() {
      const { data: res } = await this.$http.get("searchAllBranch");
      console.log(res);
      this.branch = res;
    },
    // 添加党支部
    addBranch() {
      // 提交请求前，表单预验证
      this.$refs.addBranchFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "addPartyBranch",
          this.$qs.stringify(this.addBranchForm)
        );
        this.$message.success("添加党支部成功！");
        // 隐藏添加用户对话框
        this.addDialogVisible = false;
        this.getBranchs();
      });
    },
    // 编辑用户信息
    async showEditDialog(id) {
      this.editTeacherID.teacherID = id;
      const { data: res } = await this.$http.get("searchMemberByTeacherID", {
        params: this.editTeacherID,
      });
      console.log(res);
      this.editUserForm = res;
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 修改用户信息
    editUser() {
      // 提交请求前，表单预验证
      this.$refs.editUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        this.tempeditUserForm.teacherID = this.editUserForm.teacherID;
        this.tempeditUserForm.phoneNumber = this.editUserForm.phoneNumber;
        this.tempeditUserForm.partyBranch = this.editUserForm.partyBranch;
        this.tempeditUserForm.isBranchLeader = this.editUserForm.isBranchLeader;
        if (this.tempeditUserForm.isBranchLeader === true) {
          this.tempeditUserForm.isBranchLeader = "是";
        } else {
          this.tempeditUserForm.isBranchLeader = "否";
        }
        this.tempeditUserForm.dues = this.editUserForm.dues;
        const { data: res } = await this.$http.put(
          "modifyPartyMember",
          this.$qs.stringify(this.tempeditUserForm)
        );
        // 隐藏添加用户对话框
        this.editDialogVisible = false;
        this.$message.success("更新用户信息成功！");
        this.getBranchUserList();
      });
    },
    // 删除用户
    async removeUserByName(tempName) {
      console.log(tempName);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      console.log(tempName);
      var temp = { name: tempName };
      console.log(temp);
      const { data: res } = await this.$http.delete("deletePartyMember", {
        params: temp,
      });
      this.$message.success("删除用户成功！");
      this.getBranchUserList();
    },
  },
};
</script>

<style lang="less" scoped>
</style>
